<template>
    <div>
        <el-breadcrumb separator-class="el-icon-caret-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>添加商品</el-breadcrumb-item>
        </el-breadcrumb>

        <el-card>
            <!--提示框-->
            <el-alert
                    title="添加商品信息" center
                    type="info"
                    effect="dark" show-icon :closable="false">
            </el-alert>

            <!--步骤条-->
            <!--active 指定激活项的索引，默认从0开始-->
            <!--activeIndex - 0 是为了转化为整数，而不是字符串-->
            <el-steps :space="200" :active="activeIndex - 0" align-center finish-status="success">
                <el-step title="基本信息"></el-step>
                <el-step title="商品参数"></el-step>
                <el-step title="商品属性"></el-step>
                <el-step title="商品图片"></el-step>
                <el-step title="商品内容"></el-step>
                <el-step title=完成></el-step>
            </el-steps>


            <el-form :model="addForm" :rules="addFormRules" label-position="top" label-width="100px" ref="addFormRef">
                <!--tab栏区域-->
                <!--激活的属性会默认绑定到v-model绑定的属性上-->
                <el-tabs v-model="activeIndex" tab-position="left" :before-leave="beforeTabLeave" @tab-click="tabClicked">
                    <!--添加商品的基本信息-->
                    <el-tab-pane label="基本信息" name="0">
                        <el-form-item label="商品名称" prop="goods_name">
                            <el-input v-model="addForm.goods_name"></el-input>
                        </el-form-item>
                        <el-form-item label="商品价格" prop="goods_price">
                            <el-input type="number" v-model="addForm.goods_price"></el-input>
                        </el-form-item>
                        <el-form-item label="商品重量" prop="goods_weight">
                            <el-input v-model="addForm.goods_weight"></el-input>
                        </el-form-item>
                        <el-form-item label="商品数量" prop="goods_number">
                            <el-input v-model="addForm.goods_number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品分类" prop="goods_cat">
                            <el-cascader
                                    v-model="addForm.goods_cat"
                                    :options="cateList"
                                    :props="caderProps"
                                    @change="handlerChange"
                            ></el-cascader>
                        </el-form-item>
                    </el-tab-pane>

                    <!--商品参数添加列表-->
                    <el-tab-pane label="商品参数" name="1">
                        <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
                            <!--会自动绑定到数组上，每次修改会自动更新绑定的数组-->
                            <el-checkbox-group v-model="item.attr_vals" >
                                <el-checkbox :label="cd" v-for="(cd ,i) in item.attr_vals" border :key="i"></el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-tab-pane>

                    <!--商品属性列表-->
                    <el-tab-pane label="商品属性" name="2">
                        <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
                            <el-input v-model="item.attr_vals"></el-input>
                        </el-form-item>
                    </el-tab-pane>

                    <!--图片的上传-->
                    <el-tab-pane label="商品图片" name="3">
                        <!--action :图片要上传的API地址，需要一个完整的API地址，不然就是当前路径下的拼接路径-->
                        <!--on-preview：指定阅览的事件-->
                        <!--handleRemove: 处理移除图片的操作-->
                        <!--list-type : 指定图片上传的效果-->
                        <!--文件上传的不是使用的axios发送的Ajax请求，而是使用自带的Ajax的发送，必须手动的指定headers字段-->
                        <el-upload
                                :headers="uploadHeaders"
                                :action="uploadUrl"
                                :on-preview="handlePreview"
                                :on-remove="handleRemove"
                                type="file"
                                list-type="picture"
                                :on-success="uploadSuccess"
                                >
                            <el-button size="small" type="primary">点击上传</el-button>
                        </el-upload>
                    </el-tab-pane>

                    <el-tab-pane label="商品内容" name="4">
                        <quill-editor
                                ref="myQuillEditor"
                                v-model="addForm.goods_introduce"
                        ></quill-editor>
                        <el-button type="primary" style="margin-top: 20px" @click="add">添加商品</el-button>
                    </el-tab-pane>
                </el-tabs>

            </el-form>
        </el-card>

        <!--图片阅览的对话框-->
        <el-dialog
                title="图片预览"
                :visible.sync="setPreviewDialog"
                width="50%"
                >
            <img :src="previewPath" class="imagePreview"/>
        </el-dialog>

    </div>
</template>

<script>
    import _ from 'lodash'
    export default {
        name: "Add",
        data() {
            return {
                //激活项
                activeIndex: 0,

                //添加商品的表单数据对象
                addForm: {
                    //商品所属的分类数组
                    goods_cat: [],
                    //图片上传成功后的图片的数组
                    pics: [],
                    //商品的详情描述
                    goods_introduce: '',
                    //商品的参数（数组），包含 动态参数 和 静态属性
                    attrs: [],
                },

                //校验规则
                addFormRules: {
                    goods_name: [
                        {required: true, message: "请输入商品名称", trigger: 'blur'}
                    ],
                    goods_price: [
                        {required: true, message: "请输入商品价格", trigger: 'blur'}
                    ],
                    goods_weight: [
                        {required: true, message: "请输入商品重量", trigger: 'blur'}
                    ],
                    goods_number: [
                        {required: true, message: "请输入商品数量", trigger: 'blur'}
                    ],
                    goods_cat: [
                        {required: true, message: "请选择商品分类", trigger: 'blur'}
                    ]

                },
                //商品分类数组
                cateList: [],

                caderProps: {
                    expandTrigger: 'hover',
                    label: 'cat_name',
                    value: 'cat_id',
                    children: 'children'
                },

                //商品参数的列表数组
                manyTableData: [],

                //商品的静态属性数组
                onlyTableData:[],

                //上传图片的Url地址
                uploadUrl: "http://127.0.0.1:8888/api/private/v1/upload",

                //文件上传的请求头
                uploadHeaders: {authorization: window.sessionStorage.getItem("token")},

                //阅览图片的完整路径值
                previewPath: "",

                //图片阅览框的显示
                setPreviewDialog: false,

            }

        },
        computed: {
            //选中的商品的Id
            cateId(){
                if (this.addForm.goods_cat.length === 3){
                    return this.addForm.goods_cat[2]
                }
            },

        },
        created() {

            this.getCateList();

        },

        methods: {
            async getCateList() {
                const {data} = await this.$http.get('categories');
                if (data.meta.status !== 200) return this.$message.error('获取商品信息失败');
                this.cateList = data.data;
            },

            //级联选择器选中后触发的事件
            handlerChange(){
                //让其必须选择三级分类
                if (this.addForm.goods_cat.length !== 3){
                    this.addForm.goods_cat = [];
                }
            },

            //标签页切换之前的钩子函数
            beforeTabLeave(activeName,oldActiveName){
                if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3){
                    this.$message.error('请选择商品分类');
                    return false
                }
            },

            //tags选中的事件
            async tabClicked(){
                if (this.activeIndex === '1'){
                    //访问的动态参数面板
                 const {data} = await this.$http.get(`categories/${this.cateId}/attributes`,{params: {sel: 'many'}});
                    if (data.meta.status !== 200) return this.$message.error(data.meta.msg);
                    data.data.forEach(item => {
                        item.attr_vals = item.attr_vals.length ===0  ? [] : item.attr_vals.split(' ');
                    });
                    this.manyTableData = data.data;

                }else if (this.activeIndex === '2'){
                    //访问的静态属性面板
                    const {data} = await this.$http.get(`categories/${this.cateId}/attributes`,{params: {sel: 'only'}});
                    if (data.meta.status !== 200) return this.$message.error(data.meta.msg);
                    this.onlyTableData = data.data;
                }
            },

            //处理图片的预览效果
            handlePreview(file){
                this.setPreviewDialog = true;
                this.previewPath = file.response.data.url;
            },

            //处理移除图片的操作
            //file 移除的图片的信息
            handleRemove(file){
                const index = this.addForm.pics.findIndex(x => x.pic === file.response.data.tmp_path);
                //从pics数组中获取对应的图片的索引值
                this.addForm.pics.splice(index,1);
            },

            //图片上传成功后的处理函数
            //response 上传成功后返回的数据
            uploadSuccess(response){
                const picPath = {pic : response.data.tmp_path};
                this.addForm.pics.push(picPath);
            },

            //最后的添加商品
            add(){
                this.$refs.addFormRef.validate(async valid => {
                    if (!valid){
                        return this.$message.error('请填写必要的表单项');
                    }
                    //我们需要将addForm中的goods_cat转为字符串
                    //级联选择器需要绑定的一定是一个数组，一旦转换就会出错
                    //lodash 进行深拷贝，操作新的绑定数组
                    const form  = _.cloneDeep(this.addForm);
                    form.goods_cat = form.goods_cat.join(',');
                    //还需要处理attrs
                    this.handleAttrs();
                    form.attrs = this.addForm.attrs;
                    //发起请求添加商品
                    const {data} = await this.$http.post(`goods`,form);
                    if (data.meta.status !== 201) return this.$message.error(data.meta.msg);
                    this.$message.success('添加成功');
                });
                this.$router.push('/goods');
            },

            //处理静态参数以及静态属性，转为指定的格式
            handleAttrs(){
                this.manyTableData.forEach(item => {
                    const newInfo = {attr_id: item.attr_id, attr_value: item.attr_vals.join(' ')};
                    this.addForm.attrs.push(newInfo)
                });
                this.onlyTableData.forEach(item => {
                    const newInfo = {attr_id: item.attr_id, attr_value: item.attr_vals};
                    this.addForm.attrs.push(newInfo)
                });
            },

        }
    }
</script>

<style scoped>

    .el-checkbox{
        margin: 0 10px 0 0 !important;
    }
    .imagePreview{
        width: 100%;
    }

</style>
